using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Routing;
using Isis.Helpers.Impl;
using Isis.Helpers.Interfaces;
using Isis.Interfaces;
using Isis.Model;
using Isis.Views;

namespace Isis.Controllers
{
    public class RoutesController : IControlPanelController
    {
        private readonly string _basePath;
        private readonly IKeyValueListHelper _keyValueListHelper;

        public RoutesController(string basePath)
        {
            _basePath = basePath;
            _keyValueListHelper = new KeyValueListHelper();
        }

        public void Render(TextWriter writer)
        {
            var pageLayoutWriter = new PageLayoutWriter(Tab.Title, Action, new ControllerRepository(), _basePath);
            pageLayoutWriter.RenderPage(writer, RenderContent);
        }

        private void RenderContent(TextWriter writer)
        {
            var tableHelper = new TableRenderingHelper();
            writer.Write(tableHelper.RenderTableHeader("Registered Routes"));
            writer.Write(tableHelper.RenderHeaderRow("Pattern", "Default Values", "Constraints", "Data Tokens", "Handler"));

            RouteCollection routeCollection = RouteTable.Routes;
            foreach (Route route in routeCollection)
            {
                string defaultValues = _keyValueListHelper.ToKeyValueList(route.Defaults);
                string constraints = _keyValueListHelper.ToKeyValueList(route.Constraints);
                string dataTokens = _keyValueListHelper.ToKeyValueList(route.DataTokens);
                string routeHandlerType = route.RouteHandler.GetType().Name;

                var row = new[] { route.Url, defaultValues, constraints, dataTokens, routeHandlerType };
                writer.Write(tableHelper.RenderRow(row));
            }
            writer.Write("</table>");
        }

        public ControllerTab Tab
        {
            get { return new ControllerTab("Routes"); }
        }

        public string Action { get; set; }
        public string Parameter { get; set; }

        public IEnumerable<string> SubTabs
        {
            get { return new string[] {}; }
        }
    }
}